package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.GlobalException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.dto.*;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.CourseCategory;
import com.xuecheng.content.entity.CourseMarket;
import com.xuecheng.content.entity.Teachplan;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author FengHuan Wang
 * @Date 2025/3/29 9:43
 * @Version 1.0
 */
@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Resource
    CourseBaseMapper courseBaseMapper;

    @Resource
    CourseMarketMapper courseMarketMapper;

    @Resource
    CourseCategoryMapper courseCategoryMapper;

    @Resource
    TeachplanMapper teachplanMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {

        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        // 构建查询条件
        QueryCourseParamsDto queryCourseParams = new QueryCourseParamsDto();
        queryCourseParams.setCourseName("java");
        queryCourseParams.setAuditStatus("202004");
        queryCourseParams.setPublishStatus("203001");
        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParams.getCourseName()), CourseBase::getName, queryCourseParams.getCourseName());
        // 根据课程审核状态
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParams.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParams.getAuditStatus());
        // 分页参数
        PageParams pageParam = new PageParams();
        pageParam.setPageNo(1L);
        pageParam.setPageSize(3L);
        Page<CourseBase> page = new Page<>(pageParam.getPageNo(), pageParam.getPageSize());
        // 分页查询
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        // 数据
        List<CourseBase> items = pageResult.getRecords();
        // 总记录数
        Long total = pageResult.getTotal();
        // 准备返回数据
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(items, total, pageParam.getPageSize());
        return courseBasePageResult;
    }

    /**
     * 新增课程
     * @param companyId
     * @param addCourseDto
     * @return
     */
    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {

        // 参数的合法性校验
        if (addCourseDto == null){
            throw new RuntimeException("请求参数有误");
        }
        // 向课程基本信息表中写入数据
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto, courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        courseBase.setAuditStatus("202002");
        courseBase.setStatus("203001");
        // 插入课程基本信息表
        int insert = courseBaseMapper.insert(courseBase);
        if (insert <= 0){
            throw new GlobalException("新增课程基本信息失败");
        }
        // 向课程营销表中去写入数据
        CourseMarket courseMarket = new CourseMarket();
        Long id = courseBase.getId();
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        courseMarket.setId(id);
        int i = saveCourseMarket(courseMarket);
        if (i <= 0){
            throw new GlobalException("保存课程营销信息失败");
        }
        // 查询课程基本信息以及营销信息并返回
        return getCourseBaseInfo(id);
    }
    /**
     * 保存课程营销信息
     * @param courseMarket
     * @return
     */
    private int saveCourseMarket(CourseMarket courseMarket){
        // 收费规则
        String charge = courseMarket.getCharge();
        if (StringUtils.isBlank(charge)){
            throw new GlobalException("收费规则为空");
        }
        if ("201001".equals(charge)){
            if (courseMarket.getPhone() == null || courseMarket.getPrice().floatValue() <= 0){
                throw new GlobalException("课程收费价格设置不合理");
            }
        }
        // 根据id从课程营销表中查询
        CourseMarket courseMarketObj = courseMarketMapper.selectById(courseMarket.getId());
        if (courseMarketObj == null){
            return courseMarketMapper.insert(courseMarket);
        }else {
            BeanUtils.copyProperties(courseMarket, courseMarketObj);
            courseMarketObj.setId(courseMarket.getId());
            return courseMarketMapper.updateById(courseMarketObj);
        }
    }

    /**
     * 根据课程id查询课程基本西南西，包括基本信息和营销信息
     * @param courseId
     * @return
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null){
            throw new GlobalException("课程为空");
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        if (courseMarket != null){
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        // 查询分类名称
        CourseCategory courseCategory = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategory.getName());
        CourseCategory courseCategory1 = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategory1.getName());
        return  courseBaseInfoDto;
    }

    /**
     * 修改课程
     * @param companyId
     * @param editCourseDto
     * @return
     */
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {

        Long courseId = editCourseDto.getCourseId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null){
            throw new GlobalException("课程不存在");
        }
        // 数据合法性校验
        if (companyId == null){
            throw new GlobalException("请求参数错误");
        }
        if (!companyId.equals(courseBase.getCompanyId())){
            throw new GlobalException("不能修改其他机构的课程");
        }
        BeanUtils.copyProperties(editCourseDto, courseBase);
        courseBase.setCreateDate(LocalDateTime.now());
        // 向课程营销表中去写入数据
        CourseMarket courseMarket = new CourseMarket();
        Long id = courseBase.getId();
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        courseMarket.setId(id);
        int i = saveCourseMarket(courseMarket);
        if (i <= 0){
            throw new GlobalException("保存课程营销信息失败");
        }
        int update = courseBaseMapper.updateById(courseBase);
        if (update <= 0){
            throw new GlobalException("修改失败");
        }
        return getCourseBaseInfo(courseId);
    }

    /**
     * 保存课程计划
     * @param saveTeachplanDto
     */
    @Override
    @Transactional
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        // 课程计划id
        Long id = saveTeachplanDto.getId();
        // 修改课程计划
        if (id != null){
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        }else {
            // 取出同父级别的课程计划数量
            int count = getTeachplanCount(saveTeachplanDto.getCourseId(), saveTeachplanDto.getParentId());
            Teachplan teachplanNew = new Teachplan();
            // 设置排序号
            teachplanNew.setOrderby(count + 1);
            BeanUtils.copyProperties(saveTeachplanDto, teachplanNew);
        }
    }

    /**
     * 获取最新的排序号
     * @param courseId
     * @param parentId
     * @return
     */
    private int getTeachplanCount(Long courseId, Long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId);
        queryWrapper.eq(Teachplan::getParentid, parentId);
        Integer integer = teachplanMapper.selectCount(queryWrapper);
        return integer;
    }
}
